package easy;

import java.util.ArrayList;
import java.util.List;
import util.PrintUtils;

public class Solution_1337 {

    public int[] kWeakestRows(int[][] mat, int k) {
        int[] counts = new int[mat.length];
        for (int i = 0; i < mat.length; i++) {
            int[] ints = mat[i];
            for (int num : ints) {
                counts[i] += num;
            }
        }

        List<Integer>[] arr = new List[10001];
        for (int i = 0; i < counts.length; i++) {
            List<Integer> list = arr[counts[i]];
            if (list == null) {
                list = new ArrayList<>();
            }
            list.add(i);
            arr[counts[i]] = list;
        }
        int[] res = new int[k];
        for (int i = 0, index = 0; index < k && i < arr.length; i++) {
            if (arr[i] != null) {
                for (Integer integer : arr[i]) {
                    res[index++] = integer;
                    if (index == k) {
                        break;
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution_1337 model = new Solution_1337();
        PrintUtils.arrayInt(model.kWeakestRows(new int[][]{{1, 0, 0, 0},
            {1, 1, 1, 1},
            {1, 0, 0, 0},
            {1, 0, 0, 0}}, 2));
        PrintUtils.arrayInt(model.kWeakestRows(new int[][]{{1, 1, 0, 0, 0},
            {1, 1, 1, 1, 0},
            {1, 0, 0, 0, 0},
            {1, 1, 0, 0, 0},
            {1, 1, 1, 1, 1}}, 3));
    }
}
